package com.situ.Servlet.CokieSevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.filters.AddDefaultCharsetFilter;

public class ListTimeServlet extends HttpServlet {
	/**
	 * 获取时间，通过浏览器打印上一次登陆的时间
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//将时间推到浏览器Cookie里面
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = simpleDateFormat.format(date);
		Cookie cookie = new Cookie("LastTime", time);
		resp.addCookie(cookie);
		
		//获取cookie里的时间
		String lastTime = null;
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cook : cookies) {
				if (cook.getName().equals("LastTime")) {
					lastTime = cook.getValue();
					System.out.println(lastTime);
				}
			}
		}
		
		//浏览器打印
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if (writer == null) {
			writer.println("第一次登陆");
		}else {
			writer.print("上次访问的时间： " + lastTime);
		}
	}
}
